package org.example.controller;

import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.domain.*;
import org.example.dto.Dishdto;
import org.example.service.*;
import org.example.service.impl.DishServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    DishService dishService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    DishFlavorService dishFlavorService;
    @Autowired
    SetmealService setmealService;
    @Autowired
    SetmealDishService setmealDishService;

    @PostMapping
    public R<String> save(@RequestBody Dishdto dishdto, HttpServletRequest request) {
        dishService.saveWithFlavor(dishdto);
        HttpSession session = request.getSession();
        Object imglist = session.getAttribute("imglist");
        List<String> img = (List<String>) imglist;
        if (img.size() > 0) {

            for (int i = 0; img.get(i) != null && (i < img.size()); i++) {
                if (img.get(i).equals(dishdto.getImage())) {
                    img.remove(i);

                }
                break;
            }
        }
        session.setAttribute("imglist", img);
        return R.success("success");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Dish> dishPage = new Page<Dish>(page, pageSize);
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<Dish>();
        dishLambdaQueryWrapper.like(name != null, Dish::getName, name);
        dishService.page(dishPage, dishLambdaQueryWrapper);
        Page<Dishdto> dishdtoPage = new Page<>(page, pageSize);
        BeanUtils.copyProperties(dishPage, dishdtoPage, "records");
        List<Dishdto> dishdtos = new ArrayList<>();
        List<Dish> records = dishPage.getRecords();
        for (Dish dish :
                records) {
            Dishdto dishdto = new Dishdto();
            BeanUtils.copyProperties(dish, dishdto);
            Category category = categoryService.getById(dish.getCategoryId());
            dishdto.setCategoryName(category.getName());
            dishdtos.add(dishdto);
        }
        dishdtoPage.setRecords(dishdtos);
        return R.success(dishdtoPage);

    }

    @GetMapping("/{id}")
    public R<Dishdto> getDishById(@PathVariable long id) {
        Dishdto dishdto = dishService.getByIdWithFlavor(id);
        return R.success(dishdto);
    }

    @PutMapping
    public R<String> updataById(@RequestBody Dishdto dishdto) {
        dishService.updataWithDishFlavor(dishdto);
        return R.success("success");
    }

    //    @GetMapping("/list")
//    public R<List<Dish>> getById(Dish dish){
//        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        LambdaQueryWrapper<Dish> queryWrapper = dishLambdaQueryWrapper.eq(Dish::getCategoryId, dish.getCategoryId()).orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        List<Dish> list = dishService.list(queryWrapper);
//        return R.success(list);
//    }
    @GetMapping("/list")
    public R<List<Dishdto>> list(Dish dish) {
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus, 1);

        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        List<Dishdto> dishDtoList = list.stream().map((item) -> {
            Dishdto dishDto = new Dishdto();

            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }

    @Transactional
    @PostMapping("status/{status}")
    public R<String> setStatus(@PathVariable int status, Long[] ids) {
        for (Long id :
                ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(status);
            dishService.updateById(dish);
            LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            setmealDishLambdaQueryWrapper.eq(SetmealDish::getDishId, id);
            List<SetmealDish> list = setmealDishService.list(setmealDishLambdaQueryWrapper);
            int size = list.size();
            if (size > 0) {

                Long setmealId = list.get(0).getSetmealId();
                Setmeal setmeal = setmealService.getById(setmealId);
                setmeal.setStatus(status);
                setmealService.updateById(setmeal);
            }
        }
        return R.success("ok");
    }

    @DeleteMapping
    public R<String> del(Long[] ids) {
        for (Long id :
                ids) {
            Dish dish = dishService.getById(id);
            String image = dish.getImage();
            HashMap<String, Object> objectObjectHashMap = new HashMap<>();
            objectObjectHashMap.put("body", image);
            String post = HttpUtil.get("http://localhost:8080/gitee/del", objectObjectHashMap);


        }
        for (Long id :
                ids) {
            LambdaQueryWrapper<SetmealDish> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
            setmealLambdaQueryWrapper.eq(SetmealDish::getDishId, id);
            if (setmealDishService.count(setmealLambdaQueryWrapper) > 0) {
                return R.error("套餐在售");
            }
            dishService.removeById(id);

        }
        return R.success("成功");
    }
}
